package com.manor.common.http;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.MemoryCookieStore;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.manor.common.CommonAppConfig;
import com.manor.common.CommonAppContext;
import com.manor.common.utils.DateUtil;
import com.manor.common.utils.MD5Util;
import com.manor.common.utils.NetworkUtils;
import com.manor.common.utils.SpUtil;

import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by cxf on 2018/9/17.
 */

public class HttpClient {

    public static final String SALT = "HYTFbh0Y9hc709JSGWcbfvSN3LvJaYFA";
    public static final String S_JAVA = "MjUa2rI3cBwvdAubD7D";
    public static final int TIMEOUT = 10 * 1000;
    private static HttpClient sInstance;
    private OkHttpClient mOkHttpClient;
    private String mLanguage;//语言
    private String mUrl;
    private String JAVA_HOST;
    private HttpClient() {
        mUrl = CommonAppConfig.HOST + "ricelifeapi/ricelifeapi/?service=";
        JAVA_HOST  = CommonAppConfig.JAVA_HOST;;
    }

    public static HttpClient getInstance() {
        if (sInstance == null) {
            synchronized (HttpClient.class) {
                if (sInstance == null) {
                    sInstance = new HttpClient();
                }
            }
        }
        return sInstance;
    }

    public void init() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
       // MyHttpLogInterceptor interceptor = new MyHttpLogInterceptor();
       // builder.addInterceptor(interceptor);
        builder.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
        builder.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
        builder.writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
        builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));
        builder.retryOnConnectionFailure(true);

        builder.proxy(Proxy.NO_PROXY);
        builder.proxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Collections.singletonList(Proxy.NO_PROXY);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

            }
        });



//        Dispatcher dispatcher = new Dispatcher();
//        dispatcher.setMaxRequests(20000);
//        dispatcher.setMaxRequestsPerHost(10000);
//        builder.dispatcher(dispatcher);

        //输出HTTP请求 响应信息
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OKGO");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
        mOkHttpClient = builder.build();

        OkGo.getInstance().init(CommonAppContext.sInstance)
                .setOkHttpClient(mOkHttpClient)
                .setCacheMode(CacheMode.NO_CACHE)
                .setRetryCount(1);



    }

    public GetRequest<JsonBean> get(String serviceName, String tag) {
        return OkGo.<JsonBean>get(mUrl + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }


    public GetRequest<JsonBeanX> getX(String serviceName, String tag) {
        return OkGo.<JsonBeanX>get(mUrl + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }
    public PostRequest<JsonBeanX> postX(String serviceName, String tag) {
        return OkGo.<JsonBeanX>post(mUrl + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }

    public GetRequest<JsonBean> get(String url,String serviceName, String tag) {
        return OkGo.<JsonBean>get(url + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }

    public PostRequest<JsonBean> post(String serviceName, String tag) {
        return OkGo.<JsonBean>post(mUrl + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }

    @SuppressLint("MissingPermission")
    public PostRequest<JsonBean> postSB(String serviceName, String tag) {
        return OkGo.<JsonBean>post(mUrl + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION +" || "+ NetworkUtils.getIPAd())
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }

    public PostRequest<JsonBean> post(String url,String serviceName, String tag) {
        return OkGo.<JsonBean>post(url + serviceName)
                .headers("Connection", "keep-alive")
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }


    public void cancel(String tag) {
        OkGo.cancelTag(mOkHttpClient, tag);
    }

    public void setLanguage(String language) {
        mLanguage = language;
    }



    private String getDate(){
        String date = DateUtil.getNowString(DateUtil.getDateFormat("yyyyMMdd"));
        return MD5Util.getMD5(date);
    }

    private String getDR1(){
        String token = SpUtil.getInstance().getStringValue(SpUtil.JAVA_TOKEN);
        return MD5Util.getMD5(token + "rsp" + getDate() + S_JAVA);
    }

    private String getDR2(){
        String token = SpUtil.getInstance().getStringValue(SpUtil.JAVA_TOKEN);
        if (!TextUtils.isEmpty(token) && token.length()>7){
            token = token.substring(7);
        }
        return MD5Util.getMD5(token + getDate() + S_JAVA);
    }


    public GetRequest<JJsonBean> Jget(String serviceName, String tag) {
        return OkGo.<JJsonBean>get(JAVA_HOST+ serviceName)
                .headers("admin-auth",  SpUtil.getInstance().getStringValue(SpUtil.JAVA_TOKEN))
                .headers("q", "rsp")
                .headers("version", CommonAppConfig.APP_VERSION)
                .tag(tag);
    }

    public PostRequest<JJsonBean> Jpost(String serviceName, String tag) {
        return Jpost(serviceName, tag , SpUtil.getInstance().getStringValue(SpUtil.JAVA_TOKEN));
    }


    public PostRequest<JJsonBean> Jpost(String serviceName, String tag, String token) {
        return OkGo.<JJsonBean>post(JAVA_HOST + serviceName)
                .headers("admin-auth",  token)
                .headers("q", "rsp")
                .headers("version", CommonAppConfig.APP_VERSION)
                .tag(tag);
    }


    public PostRequest<JJsonBean> jPost(String serviceName, String tag) {
        return OkGo.<JJsonBean>post(JAVA_HOST + serviceName)
                .headers("Connection", "keep-alive")
                .headers("admin-auth",  SpUtil.getInstance().getStringValue(SpUtil.JAVA_TOKEN))
                .headers("q", "rsp")
                .headers("version", CommonAppConfig.APP_VERSION)
                .tag(tag)
                .params(CommonHttpConsts.LANGUAGE, mLanguage)
                .params("version", CommonAppConfig.APP_VERSION)
                .params("model", CommonAppConfig.SYSTEM_MODEL)
                .params("system", CommonAppConfig.SYSTEM_RELEASE);
    }



}
